/**
 * 全局音频管理器
 * 确保同时只能播放一个音频文件
 */
import { ref, readonly } from 'vue'

// 当前播放的音频实例
const currentPlayingAudio = ref<HTMLAudioElement | null>(null)
// 当前播放的组件实例ID
const currentPlayingId = ref<string | null>(null)

export function useAudioManager() {
  /**
   * 注册新的音频播放
   * @param audioElement 音频元素
   * @param instanceId 组件实例ID
   */
  const registerAudioPlay = (audioElement: HTMLAudioElement, instanceId: string) => {
    // 如果有其他音频正在播放，先暂停它
    if (currentPlayingAudio.value && currentPlayingId.value !== instanceId) {
      currentPlayingAudio.value.pause()
    }
    
    // 设置当前播放的音频
    currentPlayingAudio.value = audioElement
    currentPlayingId.value = instanceId
  }

  /**
   * 取消音频播放注册
   * @param instanceId 组件实例ID
   */
  const unregisterAudioPlay = (instanceId: string) => {
    if (currentPlayingId.value === instanceId) {
      currentPlayingAudio.value = null
      currentPlayingId.value = null
    }
  }

  /**
   * 检查是否是当前播放的音频
   * @param instanceId 组件实例ID
   */
  const isCurrentPlaying = (instanceId: string) => {
    return currentPlayingId.value === instanceId
  }

  /**
   * 暂停当前播放的音频
   */
  const pauseCurrentAudio = () => {
    if (currentPlayingAudio.value) {
      currentPlayingAudio.value.pause()
    }
  }

  return {
    registerAudioPlay,
    unregisterAudioPlay,
    isCurrentPlaying,
    pauseCurrentAudio,
    currentPlayingId: readonly(currentPlayingId)
  }
}
